package cn.wolfcode.luowowo.listener;

import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.redis.RedisService.IStrategyStatisVORedisService;
import cn.wolfcode.luowowo.redis.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.service.IStrategyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * redis数据初始化监听器
 */
@Component//创建实例对象给Spring管理起来
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private IStrategyStatisVORedisService strategyStatisVORedisService;

    //spring容器准备好之后马上执行的方法
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
//1.查找SpringBoot中所有攻略
        List<Strategy> list = strategyService.list();
// 2.遍历这些方法对象封装攻略统计vo对象
        for (Strategy s : list) {
            //第一次初始化完成之后，如果页面进行操作，redis数据会发生变动，在没有持久化入库前，前再次启动
            //如果不做跳过处理，会出现旧数据覆盖信息数据

            //如果redis已经存在vo对象，直接跳过
            if (strategyStatisVORedisService.isVOExists(s.getId())) {
                continue;
            }
//添加到redis
            StrategyStatisVO vo = new StrategyStatisVO();
            BeanUtils.copyProperties(s, vo);
            vo.setStrategyId(s.getId());
            strategyStatisVORedisService.setStatisVo(vo);
        }
    }
}
